<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="作品名称" prop="workName">
        <el-input v-model="queryParams.workName" placeholder="请输入作品名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="分类编号" prop="catagoryId">
          <el-select v-model="oneWorkCategoryId" placeholder="请选择一级分类" @change="changeOneCategory" style="width: 140px;">
            <el-option v-for="item in oneCategories" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
          <el-select v-model="queryParams.catagoryId" placeholder="请选择二级分类" style="width: 140px;">
            <el-option v-for="item in twoCategories" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
      </el-form-item>
      <el-form-item label="作品类型" prop="workType">
        <el-select v-model="queryParams.workType" placeholder="请选择作品类型" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.TD_WORK_TYPE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="是否发布" prop="published">
        <el-select v-model="queryParams.published" placeholder="请选择是否发布" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.TD_WORK_PUBLISHED)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="作品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择作品状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.TD_WORK_STATUS)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="作者名称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入作者名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <!-- <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['td:work:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading" v-hasPermi="['td:work:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" type="index"  width="100"/>
      <el-table-column label="作品名称" align="center" prop="workName" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <!-- <el-table-column label="图片" align="center" prop="imgSrc">
        <template #default="scope">
          <img :src="scope.row.imgSrc" alt="作品图片" style="width: 50px; height: 50px;" />
        </template>
      </el-table-column> -->
      
      <el-table-column label="作品类型" align="center" prop="workType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TD_WORK_TYPE" :value="scope.row.workType" />
        </template>
      </el-table-column>
      <el-table-column label="作品作者" align="center" prop="nickName" >
         <template #default="scope">
          {{ scope.row.nickName }}
        </template>
      </el-table-column>
      <el-table-column label="作品状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TD_WORK_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="是否发布" align="center" prop="published">
        
        <!-- <template #default="scope">
          <dict-tag :type="DICT_TYPE.TD_WORK_PUBLISHED" :value="scope.row.published" />
        </template> -->
        <template #default="scope">
          <!-- <span :style="{ color: scope.row.published ? 'green' : 'red' }">
            {{ scope.row.published ? '上架中' : '已下架' }}
          </span> -->
          <!-- 小圆点 -->
          <span
            :style="{
              display: 'inline-block',
              width: '8px',
              height: '8px',
              borderRadius: '50%',
              backgroundColor: scope.row.published ? 'green' : 'gray',
              marginRight: '8px'
            }"
          ></span>
          <!-- 文本 -->
          <span :style="{ color: scope.row.published ? 'green' : 'gray ' }">
            {{ scope.row.published ? '上架中' : '已下架' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column 
      label="操作" 
      align="center" 
      min-width="120px" 
      :show-overflow-tooltip="false"
      fixed="right"
      width="120px"
      >
        <template #default="scope">
          <el-button link type="primary" @click="openForm('detail', scope.row.id)">
            详情
          </el-button>
          
          
          <!-- 更多按钮 -->
          <!-- <el-dropdown trigger="click">
            <el-button link type="primary" style="margin-top: 3px;"><Icon icon="ep:d-arrow-right" />更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['td:work:update']"
                >
                  编辑
                </el-dropdown-item>

                <el-dropdown-item
                  @click="openWorksImageForm('create', scope.row.id)"
                  v-hasPermi="['td:work:create']"
                >
                  添加子作品
                </el-dropdown-item>

                <el-dropdown-item
                  @click="handlePublish(scope.row.id, scope.row.published)"
                  v-hasPermi="['td:work:update']"
                >
                  {{ scope.row.published ? '下架' : '上架' }}
                </el-dropdown-item>

                <el-dropdown-item
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['td:work:delete']"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown> -->
          <!-- <el-button link type="primary" @click="openForm('update', scope.row.id)"  v-hasPermi="['td:work:update']">
            编辑
          </el-button>
          <el-button link type="primary" @click="openWorksImageForm('create', scope.row.id)"  v-hasPermi="['td:work:update']">
            添加作品 
          </el-button> -->
           <!-- 动态显示上架/下架按钮 -->
          <!-- <el-button 
            link 
            :type="scope.row.published ? 'info' : 'success'" 
            @click="handlePublish(scope.row.id, scope.row.published)"
            v-hasPermi="['td:work:update']"
          >
            {{ scope.row.published ? '下架' : '上架' }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['td:work:delete']">
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <WorkForm ref="formRef" @success="getList" />
  <!-- 表单弹窗：添加作品 -->
  <WorksImageForm ref="worksImageFormRef"  />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { WorkApi, WorkVO } from '@/api/td/work'
import WorkForm from './WorkForm.vue'
import { WorksCatagoryApi, WorksCatagoryTreeVO } from '@/api/td/workscatagory'
// import { WorksImageApi, WorksImageVO } from '@/api/td/worksimage' // image表的ts
import WorksImageForm from '@/views/td/worksimage/WorksImageForm.vue' // image表的表单组件

// 为 WorksImageForm 分配独立的 ref
const worksImageFormRef = ref()
/** 作品 列表 */
defineOptions({ name: 'Work' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<WorkVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  workName: undefined,
  catagoryId: undefined,
  workType: undefined,
  published: undefined,
  userId: undefined,
  createTime: [],
  nickName: undefined,
  status: undefined,
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WorkApi.getWorkPage(queryParams)
    list.value = data.list
    total.value = data.total
  
  } finally {
    loading.value = false
  }
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {

  formRef.value.open(type, id)
}
/** 打开添加作品表单 */
// const openWorksImageForm = (type: string, workId: number) => {
//   worksImageFormRef.value.open(type, workId)
// }
/** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await WorkApi.deleteWork(id)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//   } catch {
//     // 如果有异常，提示错误信息
//     message.error(t('删除失败'))
//    }
// }

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await WorkApi.exportWork(queryParams)
    download.excel(data, '作品.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const oneWorkCategoryId=ref(undefined)

const oneCategories = ref<WorksCatagoryTreeVO[]>([]) // 一级分类
const twoCategories=ref<WorksCatagoryTreeVO[]>([]) //二级分类
const getCategoryList = async (parentId:number) => {
  loading.value = true
  try {
    const data = await WorksCatagoryApi.getListByParentId(parentId)
    oneCategories.value=data

  } finally {
    loading.value = false
  }
}

const changeOneCategory=async(id:number)=>{
  const data=await WorksCatagoryApi.getListByParentId(id)
  twoCategories.value=data

}
/** 初始化 **/
onMounted(() => {
  getList()
  getCategoryList(0)
})
/** 上架/下架按钮操作 */
// const handlePublish = async (id: number, published: boolean) => {
//   try {
//     // 弹出确认提示框
//     const confirmMessage = published ? '确定要下架该作品吗？' : '确定要上架该作品吗？'
//     await message.confirm(confirmMessage)


//     // 调用后端接口更新发布状态
//     await WorkApi.updatePublishedStatus(id, !published)

//     // 提示成功信息
//     message.success(published ? '下架成功' : '上架成功')

//     // 刷新列表
//     await getList()
//   } catch {
//     // 如果用户取消操作或请求失败，不做任何处理
//   }
// }

</script>